import express from "express";
import importRoutes from "./import.mjs";

const router = express.Router();

// 使用导入路由
router.use("/import", importRoutes);

/**
 * @swagger
 * /api/province:
 *   get:
 *     summary: 获取所有省份数据
 *     description: 获取所有省份数据
 *     responses:
 *       200:
 *         description: 省份数据获取成功
 */
router.get("/", async (req, res) => {
  try {
    const provinces = await Province.find();
    res.json(provinces);
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
});

/**
 * @swagger
 * /api/province/{name}:
 *   get:
 *     summary: 根据省份名称获取数据
 *     description: 根据省份名称获取数据
 *     responses:
 *       200:
 *         description: 数据获取成功
 */
// 根据省份名称获取数据
router.get("/:name", async (req, res) => {
  try {
    const province = await Province.findOne({ name: req.params.name });
    if (!province) {
      return res.status(404).json({ message: "未找到该省份数据" });
    }
    res.json(province);
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
});

/**
 * @swagger
 * /api/province/{name}/stats/{year}:
 *   get:
 *     summary: 获取特定年份的统计数据
 *     description: 获取特定年份的统计数据
 *     responses:
 *       200:
 *         description: 数据获取成功
 */
router.get("/:name/stats/:year", async (req, res) => {
  try {
    const province = await Province.findOne({ name: req.params.name });
    if (!province) {
      return res.status(404).json({ message: "未找到该省份数据" });
    }

    const year = parseInt(req.params.year);
    const stats = {};

    province.statistics.forEach((stat) => {
      const yearData = stat.yearlyData.find((y) => y.year === year);
      if (yearData) {
        stats[stat.name] = {
          value: yearData.value,
          unit: stat.unit,
        };
      }
    });

    res.json({
      name: province.name,
      year,
      stats,
    });
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
});

export default router;
